// src/services/survey.js
import axios from 'axios';

//传入surveyDate为问卷对象，携带着标题，描述，问题，提交问卷
export const createSurvey = async (surveyData) => {
  try {
    const response = await axios.post('http://localhost:3000/api/surveys', surveyData, {
      headers: {
        //进行身份验证
        Authorization: `Bearer ${localStorage.getItem('token')}`
      }
    });
    //返回问卷的数据，其中包括问卷的用于获取问卷的链接
    return response;
  } catch (error) {
    throw new Error('创建失败: ' + error.response?.data?.message);
  }
};

//传入问卷的id用于请求问卷的链接
export const publishSurvey = async (surveyId) => {
  try {
    const response = await axios.put(`http://localhost:3000/api/surveys/${surveyId}/publish`, null, { 
      headers: {
        Authorization: `Bearer ${localStorage.getItem('token')}`
      }
    });
    return response.data.link;
  } catch (error) {
    throw new Error('发布失败: ' + error.response?.data?.message);
  }

};

// 获取问卷的列表
export const fetchUserSurveys = async (email) => {
  const token = localStorage.getItem('token'); 
  const res = await fetch(`http://localhost:3000/api/surveys/${email}`, {
    headers: {
      Authorization: `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
  });
  const result = await res.json();
  if (!result.success) {
    throw new Error(result.message);
  }

  return result.data;
};

//修改状态
export const updateSurveyStatus = async (surveyId, status) => {
  const token = localStorage.getItem('token');
  const url = `http://localhost:3000/api/surveys/${surveyId}/${status}`;

  try {
    const response = await axios.put(url, null, {
      headers: {
        Authorization: `Bearer ${token}`,
      },
    });
    return response.data;
  } catch (error) {
    throw new Error(`修改状态失败: ${error.response?.data?.message || error.message}`);
  }
};


// 通过问卷 id 获取问卷（用于填写问卷）
export const fetchSurveyById = async (surveyId) => {
  console.log(surveyId);
  try {
    const token = localStorage.getItem('token');
    const res = await fetch(`http://localhost:3000/api/surveys/link/${surveyId}`, {
      headers: {
        Authorization: `Bearer ${token}`,
        'Content-Type': 'application/json',
      }
    }); 
    const result = await res.json();
    console.log("根据链接获取问卷",result);
    
    if (!res.ok) {
      throw new Error(result.message);
    }

    return result.data;
  } catch (error) {
    throw new Error('获取问卷失败: ' + error.message);
  }
};


// 提交问卷答案
export const submitSurveyAnswers = async (surveyId, email, answers) => {
  try {
    const response = await axios.post(`http://localhost:3000/api/surveys/${surveyId}/${email}/submit`, answers, {
      headers: {
        Authorization: `Bearer ${localStorage.getItem('token')}`,
      },
    });
    return response.data;
  } catch (error) {
    throw new Error(error.response?.data?.message || '提交失败');
  }
};

// 获取用户填写过的所有问卷答案
export const fetchUserAnswers = async (email) => {
  try {
    const token = localStorage.getItem('token');
    const res = await fetch(`http://localhost:3000/api/users/${email}/answers`, {
      headers: {
        Authorization: `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
    });
    const result = await res.json();
    if (!result.success) throw new Error(result.message);
    return result.data;
  } catch (error) {
    throw new Error('获取填写记录失败: ' + error.message);
  }
};
//根据id取得问卷问题
export const fetchSurveyByIdAny = async (id) => {
  const res = await axios.get(`http://localhost:3000/api/any/surveys/${id}`);
  if (!res.data.success) throw new Error(res.data.message);

  
  return res.data.data;
};

//通过问卷的id获取答案
export const fetchSurveyAnswers = async (surveyId) => {
  const res = await axios.get(`http://localhost:3000/api/surveys/${surveyId}/answers`);
  return res.data.data;
};